<template>
  <el-dialog
    v-model="showDialog"
    title="发现新版本是否立即更新？"
    width="700"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="dialog-body">
      <div v-if="isUpdating" class="downloading">
        <el-alert title="正在下载中..." type="success" :closable="false" />
        <el-progress :percentage="percent" :stroke-width="15" striped striped-flow :duration="10" />
      </div>
      <div v-else>
        <p class="current-version-label">当前版本：{{ updateInfo.currentVersion }}</p>
        <p>最新版本：{{ updateInfo.version }}</p>
      </div>
    </div>

    <template #footer>
      <div v-if="!isUpdating" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleDownload"> 立即更新 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { bridgeKeys } from '@renderer/utils/dicts';
import { ElMessageBox } from 'element-plus';

defineOptions({
  name: 'UpdateDownload',
});

const isUpdating = ref(false);
const updateInfo = ref({});
const downloadingInfo = ref({});
const showDialog = ref(false);

const percent = computed(() => {
  return (downloadingInfo.value.percent || 0).toFixed(2) * 1;
});

function handleClose() {
  showDialog.value = false;
}

function handleDownload() {
  // 立即更新
  window.preloadApi.startDownload();
  isUpdating.value = true;
}

/*监听下载进度*/
function onDownloadProgress() {
  window.electron.ipcRenderer.on(bridgeKeys.downloadProgress, (event, info) => {
    console.log('监听下载进度', info);
    downloadingInfo.value = info;
  });
}

/*已下载完成*/
function updateDownloaded() {
  window.electron.ipcRenderer.on(bridgeKeys.updateDownloaded, async () => {
    try {
      handleClose();
      await ElMessageBox.confirm('已下载完成，需要重启应用更新', '提示', {
        type: 'warning',
        confirmButtonText: '立即安装',
        showCancelButton: false,
      });
      window.preloadApi.quitAndInstall(); // 退出并安装
    } catch (e) {
      console.error(e);
      window.preloadApi.quitAndInstall(); // 退出并安装
    }
  });
}

/*有新版本是触发该函数*/
function onUpdateAvailable() {
  window.electron.ipcRenderer.on(bridgeKeys.updateAvailable, (event, info) => {
    updateInfo.value = info;
    showDialog.value = true;
    onDownloadProgress(); // 监听下载进度
    updateDownloaded(); // 已下载完成
  });
}

onMounted(() => {
  onUpdateAvailable();
});
</script>

<style scoped lang="less">
.current-version-label {
  margin-bottom: 10px;
}
</style>
